package com.estronger.shopmanage.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

import com.estronger.shopmanage.R;

public class WiperSwitch extends View implements OnTouchListener{
	private Bitmap bg_on, bg_off, slipper_btn;
	/**
	 * 按下时的x和当前的x
	 */
	private float downX=0, nowX=0;

	/**
	 * 记录用户是否在滑动
	 */
	private boolean onSlip = false;

	/**
	 * 当前的状态
	 */
	private boolean nowStatus = false;

	/**
	 * 监听接口
	 */
	private OnChangedListener listener;


	Paint paint = null;//画笔
	float x = 0;//滑动块的x位置


	public WiperSwitch(Context context) {
		super(context);
		init();
	}

	public WiperSwitch(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public void init(){
		//载入图片资源
		bg_on = BitmapFactory.decodeResource(getResources(), R.drawable.slide_switch2);
		bg_off = BitmapFactory.decodeResource(getResources(),  R.drawable.slide_switch3);
		slipper_btn = BitmapFactory.decodeResource(getResources(),  R.drawable.slide_switch1);

		x = 0;
		paint = new Paint();
		setOnTouchListener(this);

	}


	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
	{
		int widthMode = MeasureSpec.getMode(widthMeasureSpec);
		int widthSize = MeasureSpec.getSize(widthMeasureSpec);
		int heightMode = MeasureSpec.getMode(heightMeasureSpec);
		int heightSize = MeasureSpec.getSize(heightMeasureSpec);
		int width;
		int height ;

		boolean flagExactly=false;
		float viewWidth = (float)bg_on.getWidth();
		float viewHeight = (float)bg_on.getHeight();

		if (widthMode == MeasureSpec.EXACTLY)
		{
			width = widthSize;
			flagExactly = true;
		} else
		{
			width = (int) (viewWidth );
		}

		if (heightMode == MeasureSpec.EXACTLY)
		{
			height = heightSize;
			flagExactly = true;
		} else
		{
			height = (int) ( viewHeight );
		}

		//如果是指定大小，且宽高值确实不一致了，要重新调整图片的大小
		if( flagExactly && ( (width!=viewWidth) || (height!=viewHeight) )){
			//限制调整的范围：最大3倍，比例需要保持（要调比例，换原始图片）
			//按比例，取小值
			float ratio = Math.min(width/viewWidth, height/viewHeight);
			if(ratio > 3){
				ratio = 3;
			} else if(ratio < 1/3){
				ratio = 1/3;
			}
			width=(int)(viewWidth*ratio);
			height=(int)(viewHeight*ratio);

			bg_on = Bitmap.createScaledBitmap(bg_on, width, height, false);
			bg_off = Bitmap.createScaledBitmap(bg_off, width, height, false);
			slipper_btn = Bitmap.createScaledBitmap(slipper_btn, height, height, false);

		}

		setMeasuredDimension(width, height);
	}


	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);

		x = 0;

		if(isInEditMode()){
			return;
		}

		//根据nowStatus设置背景，开或者关状态
		if(nowStatus){
			canvas.drawBitmap(bg_on, 0, 0, paint);
		}else{
			canvas.drawBitmap(bg_off, 0, 0, paint);
		}

		if (onSlip) {//是否是在滑动状态,
			if(nowX >= bg_on.getWidth())//是否划出指定范围,不能让滑块跑到外头,必须做这个判断
				x = bg_on.getWidth() - slipper_btn.getWidth()/2;//减去滑块1/2的长度
			else
				x = nowX - slipper_btn.getWidth()/2;
		}else {
			if(nowStatus){//根据当前的状态设置滑块的x值，若不在滑动状态，非左即右！
				x = bg_on.getWidth() - slipper_btn.getWidth();
			}else{
				x = 0;
			}
		}

		//对滑块滑动进行异常处理，不能让滑块出界
		if (x < 0 ){
			x = 0;
		}
		else if(x > bg_on.getWidth() - slipper_btn.getWidth()){
			x = bg_on.getWidth() - slipper_btn.getWidth();
		}

		//画出滑块
		canvas.drawBitmap(slipper_btn, x , 0, paint);
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch(event.getAction()){
			case MotionEvent.ACTION_DOWN:{
				if (event.getX() > bg_off.getWidth() || event.getY() > bg_off.getHeight()){
					return false;
				}else{
					onSlip = true;
					downX = event.getX();
					nowX = downX;
				}
				//LogUtil.logWithMethod(new Exception(),"ACTION_DOWN: nowX="+nowX);

				getParent().requestDisallowInterceptTouchEvent(true);//禁止父ViewGroup的滑动监听

				break;
			}
			case MotionEvent.ACTION_MOVE:{
				nowX = event.getX();
				if(event.getX() >= (bg_on.getWidth()/2)){
					nowStatus = true;
				}else{
					nowStatus = false;
				}
				break;
			}
			case MotionEvent.ACTION_CANCEL:
				//LogUtil.logWithMethod(new Exception(),"ACTION_CANCEL:");
			case MotionEvent.ACTION_UP:{

				onSlip = false;
				if(event.getX() >= (bg_on.getWidth()/2)){
					nowStatus = true;
					nowX = bg_on.getWidth() - slipper_btn.getWidth();
				}else{
					nowStatus = false;
					nowX = 0;
				}
				//LogUtil.logWithMethod(new Exception(),"ACTION_UP: nowX="+nowX);
				if(listener != null){
					listener.OnChanged(WiperSwitch.this, nowStatus);
				}

				getParent().requestDisallowInterceptTouchEvent(false);//使能父ViewGroup的滑动监听

				break;
			}
		}
		//刷新界面
		invalidate();
		return true;
	}


	/**
	 * 为WiperSwitch设置一个监听，供外部调用的方法
	 * @param listener
	 */
	public void setOnChangedListener(OnChangedListener listener){
		this.listener = listener;
	}


	/**
	 * 设置滑动开关的初始状态，供外部调用
	 * @param checked
	 */
	public void setChecked(boolean checked){
		if(checked){
			nowX = bg_off.getWidth();
		}else{
			nowX = 0;
		}
		nowStatus = checked;
		invalidate();

	}


	/**
	 * 回调接口
	 * @author len
	 *
	 */
	public interface OnChangedListener {
		public void OnChanged(WiperSwitch wiperSwitch, boolean checkState);
	}


}
